import {
  AssistantListProps,
  AssistantProps,
  AssistantConfigProps,
} from '~/src/services'

export const storagePrefix = (val: string) => `sssgram.website.${val}`

export const encrypt = async (str: string) => {
  const NEXT_PUBLIC_RSA_PUBLIC_KEY = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCAdf/EyIbLBxjGqmh7qLU6/CPCzru+75+82OSPZ+nf4BFvg88drpZ6KigNW0J8TNgxe6Yms1irCZNVDyu+RXsl4y/7c2KOHc4OGTzHB5fUMiMasFUvcEs2P70e6yA/sKHZfBLG1XPhlb84Ibs3nhD3W5e2SuC+4EuVkaqzN08LQIDAQAB`
  let jsEncryptModule = await import('jsencrypt')
  let rsa = new jsEncryptModule.JSEncrypt()
  rsa.setPublicKey(NEXT_PUBLIC_RSA_PUBLIC_KEY)
  return rsa.encrypt(str)
}

export const getPageData = (
  pathName: string,
  assistantList: AssistantListProps[]
) => {
  if (!assistantList?.length) return
  let res
  for (let i = 0, len = assistantList.length; i < len; i++) {
    const assistantInfos = assistantList[i].assistantInfos
    if (!assistantInfos) {
      continue
    }
    for (let j = 0; j < assistantInfos.length; j++) {
      const currentAssistant = assistantInfos[j]
      if (pathName.indexOf(String(currentAssistant.slug).trim()) > -1) {
        res = currentAssistant
        break
      }
    }
  }

  return res
}

export const getCreateParams = (
  assistantInfo: AssistantProps,
  userInputs: any[],
  params?: { [key: string]: any }
) => {
  return {
    assistantId: assistantInfo.id,
    spaceHandle: true,
    typeCode: assistantInfo.typeCode,
    assistantCode: assistantInfo.code,
    chatId: null,
    messages: null,
    model: 'gpt-3.5-turbo',
    advancedSelectInfo: null,
    apiType: null,
    conversationId: null,
    ceateType: 'CREATE',
    secondSelectInfo: getSecondSelectInfo(
      assistantInfo.secondConfigJson.outerInfo,
      userInputs
    ),
    ...params,
  }
}

export const getSecondSelectInfo = (
  configData: AssistantConfigProps[],
  userInputs: any[]
) => {
  return configData.map((configItem, index) => ({
    outerInfoCode: configItem.code,
    itemInfoList: configItem.itemInfoList.slice(0, 1).map((item: any) => ({
      code: item.code,
      userInput: userInputs[index],
    })),
  }))
}

export const getSelectOptions = (pageData: AssistantProps, code: string) => {
  if (!pageData) return []
  const { secondConfigJson } = pageData
  const configData = secondConfigJson.outerInfo.find(
    (item) => item.code === code
  )
  return configData?.itemInfoList.map((item) => ({
    label: item.showName,
    value: item.code,
  }))
}
